<?

class Meteor {

	private $socket = false;
	private $error = null;
	static protected $instancia;

	function __construct ($host=null, $port=null) {

		$host = ($host)? $host : CONFIG_COMET_HOST;
		$port = ($port)? $port : CONFIG_COMET_PUBLISHER_PORT;

		if ($host)
			$this->connect($host, $port);
	}

	function __destruct() {
		$this->disconnect();
	}

	/**
	 * Devuelve una unica instancia de esta clase
	 * 
	 * @return object Instancia de esta clase
	 */
	public static function getInstance() {
		if (!self::$instancia instanceof self)
			self::$instancia = new self;
		return self::$instancia;
	}

	public function error ($err=null) {
		if ($err)
			$this->error = $err;
		return $this->error;
	}

	function socket () {
		return $this->socket;
	}

	function connect ($host=null, $port=null, $messages=-1) {

		// Solo permito conexion a un servidor Meteor por instancia
		if ($this->socket)
			return $this->socket;

		$host = ($host)? $host : CONFIG_COMET_HOST;
		$port = ($port)? $port : CONFIG_COMET_PUBLISHER_PORT;

		// Me conecto al servidor Meteor
		if (!($this->socket = fsockopen($host, (int)$port, $errno, $errstr, $messages))) {
			$this->error("Error al conectarse: ".$errstr);
			return false;
		}

		// Hago la conexion no bloqueante
		socket_set_blocking($this->socket,false);

		// Devuelo el socket
		return $this->socket;
	}

	function disconnect () {
		if ($this->socket)
			fclose($this->socket);
	}

	function publish ($channel, $msg) {
		$msgString = "ADDMESSAGE ".$channel." ".$msg."\n";
		fwrite($this->socket, $msgString);
	}
}

?>
